package com.lh.controller;

import com.lh.model.User;
import com.lh.service.UserService;
import com.lh.util.MyLog;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author LuoHang
 * @Date 2022-05-10 20:41
 **/
@Controller
@RequestMapping("/user")
public class LoginController {
    @Resource
    private UserService userService;

    @GetMapping("/error")
    public String error(){
        return "error";
    }

    @RequestMapping("/login")
    public String login(User user, Model model, HttpServletRequest request, HttpServletResponse response){
        User curUser = userService.login(user);
        if (curUser != null && user.getUsername() != null){
            //方案一用户持久登录案例存储在cookie中
            //Cookie username = new Cookie("username",curUser.getUsername())
            //response.addCookie(username)
            //方案二用户持久登录存储在session中
            HttpSession session = request.getSession();
            //Session会存在磁盘中，所以将User实现了序列化
            session.setAttribute("curUser",curUser);
            MyLog.info(LoginController.class,"===============登录成功===========" + curUser);
        }else {
            model.addAttribute("msg","您输入的用户名或密码不正确！！！");
        }
        return "index";
    }
}
